package cn.com.xy.sms.sdk.ui.popu.part;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.smsmessage.BusinessSmsMessage;
import cn.com.xy.sms.sdk.ui.R;
import cn.com.xy.sms.sdk.ui.popu.popupview.BasePopupView;
import cn.com.xy.sms.sdk.ui.popu.util.ChannelContentUtil;
import cn.com.xy.sms.sdk.ui.popu.util.ContentUtil;
import cn.com.xy.sms.sdk.ui.popu.util.SmartSmsSdkUtil;
import cn.com.xy.sms.sdk.ui.popu.util.ThemeUtil;
import cn.com.xy.sms.sdk.ui.popu.util.TrainDataUtil;
import cn.com.xy.sms.sdk.ui.popu.util.TravelDataUtil;
import cn.com.xy.sms.sdk.ui.popu.util.ViewUtil;
import cn.com.xy.sms.sdk.ui.popu.widget.AirTrainSelectDialog;
import cn.com.xy.sms.sdk.ui.popu.widget.SmartisanosTypeface;
import cn.com.xy.sms.sdk.ui.popu.widget.TrainArriveSelectDialog;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.util.ParseManager;
import cn.com.xy.sms.util.SdkCallBack;

public class BubbleTrainBody extends UIPart {
    public static final int MIN_CLICK_DELAY_TIME = 1000;
    private TextView mTrainNumber;
    private TextView mDepartDate;
    private TextView mArriveDate;
    private TextView mDepartTime;
    private TextView mArriveTime;
    private TextView mDepartCity;
    private TextView mArriveCity;
    private ViewGroup mArriveLay;
    private ImageView train_center_icon;
    private int mCurrentListIndex = 0;
    private JSONObject train_data;
    private JSONObject mToWebActivityJsonObject = new JSONObject();
    private ImageView leftFirstTextIcon;
    private RelativeLayout mSelectArea;
    private ImageView rightLastTextIcon;
    private JSONArray mTrainArray;
    private long lastClickTime;
    private TrianStationSelectedReceiver mRecerver;
    private String mResverFilag = "cn.com.xy.sms.TrianStationSelectedReceiver";
    private String mDepartDateString = null;
    private TrainDataUtil mTrainDataUtil = TrainDataUtil.getInstance();
    private String supplementType_1 = "1";
    private String supplementType_2 = "2";
    private SimpleDateFormat format = new SimpleDateFormat(ChannelContentUtil.TRAIN_DATE_FORMAT);
    private String mTrainSelectString = ChannelContentUtil.getResourceString(Constant.getContext(),
            R.string.duoqu_train_select);
    private ImageView mWithoutDepartDate;
    private ImageView mWithoutArriveDate;
    private ImageView mWithoutDepartTime;
    private ImageView mWithoutArriveTime;
    private ImageView mWithoutDepartAddress;
    private View mSecondSplit;
    private String mChectString;
    private String mTrainNumberString;
    private String mDepartCityString;
    private String mDepartTimeString;
    private String mArriveCityString;
    private String mArriveDateString;
    private String mArriveTimeString;
    private RelativeLayout mDateLayout;
    private static final String TAG = "BubbleTrainBody";

    private static final String SELECT_INDEX_KEY = "currentListIndex";
    private static final String MESSAGE_CHECK_KEY = "check_string";
    /* SMARTISAN-375 zhaoxiachao 20161231 start */
    private JSONArray mArriveCityArr;
    private JSONObject mArriveCityResultData;
    private int mArriveCityListIndex = 0;
    private final String DEPART_CURRENT = "depart_current";
    /* SMARTISAN-375 zhaoxiachao 20161231 end */

    public BubbleTrainBody(Activity context, BusinessSmsMessage message, XyCallBack callback, int layoutId,
            ViewGroup root, int partId) {
        super(context, message, callback, layoutId, root, partId);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void initUi() throws Exception {
        // TODO Auto-generated method stub
        super.initUi();
        mTrainNumber = (TextView) mView.findViewById(R.id.duoqu_train_number);
        mDepartDate = (TextView) mView.findViewById(R.id.duoqu_depart_date);
        mArriveDate = (TextView) mView.findViewById(R.id.duoqu_arrive_date);
        mDepartTime = (TextView) mView.findViewById(R.id.duoqu_depart_time);
        mArriveTime = (TextView) mView.findViewById(R.id.duoqu_arrive_time);
        mDepartCity = (TextView) mView.findViewById(R.id.duoqu_depart_address);
        mArriveCity = (TextView) mView.findViewById(R.id.duoqu_arrive_address);
        mArriveLay = (ViewGroup) mView.findViewById(R.id.duoqu_right_four_text_icon_layout);
        train_center_icon = (ImageView) mView.findViewById(R.id.train_center_icon);
        leftFirstTextIcon = (ImageView) mView.findViewById(R.id.duoqu_select_train_icon);
        rightLastTextIcon = (ImageView) mView.findViewById(R.id.duoqu_arrive_address_icon);
        mSelectArea = (RelativeLayout) mView.findViewById(R.id.duoqu_select_train_icon_area);
        mWithoutDepartDate = (ImageView) mView.findViewById(R.id.duoqu_depart_date_img);
        mWithoutArriveDate = (ImageView) mView.findViewById(R.id.duoqu_arrive_date_img);
        mWithoutDepartTime = (ImageView) mView.findViewById(R.id.duoqu_depart_time_img);
        mWithoutArriveTime = (ImageView) mView.findViewById(R.id.duoqu_arrive_time_img);
        mWithoutDepartAddress = (ImageView) mView.findViewById(R.id.duoqu_depart_address_img);
        mSecondSplit = mView.findViewById(R.id.duoqu_train_second_line);
        mDateLayout = (RelativeLayout) mView.findViewById(R.id.duoqu_date_layout);

        setImageAndTextColor(mMessage);
    }

    @SuppressLint("ResourceAsColor")
    private void setImageAndTextColor(BusinessSmsMessage message) {
        ThemeUtil.setTextColor(Constant.getContext(), mDepartDate, (String) message.getValue("v_by_text_5"),
                R.color.duoqu_theme_color_3010);
        ThemeUtil.setTextColor(Constant.getContext(), mArriveDate, (String) message.getValue("v_by_text_6"),
                R.color.duoqu_theme_color_3010);
        ThemeUtil.setTextColor(Constant.getContext(), mDepartTime, (String) message.getValue("v_by_text_3"),
                R.color.duoqu_theme_color_3010);
        ThemeUtil.setTextColor(Constant.getContext(), mArriveTime, (String) message.getValue("v_by_text_4"),
                R.color.duoqu_theme_color_3010);
        ThemeUtil.setTextColor(Constant.getContext(), mDepartCity, (String) message.getValue("v_by_text_1"),
                R.color.duoqu_theme_color_3010);
        ThemeUtil.setViewBg(Constant.getContext(), leftFirstTextIcon, (String) message.getValue("v_by_icon_2"),
                R.drawable.duoqu_v_by_icon_5);
        ThemeUtil.setViewBg(Constant.getContext(), rightLastTextIcon, (String) message.getValue("v_by_icon_3"),
                R.drawable.duoqu_v_by_icon_5);
        ThemeUtil.setViewBg(Constant.getContext(), train_center_icon, (String) message.getValue("v_by_icon_8"),
                R.drawable.duoqu_v_by_icon_8);
        ThemeUtil.setViewBg(Constant.getContext(), mView, "", R.drawable.duoqu_v_by_bg_1);
        
        if(SmartisanosTypeface.CLOCK != null){
            mDepartTime.setTypeface(SmartisanosTypeface.CLOCK);
            mArriveTime.setTypeface(SmartisanosTypeface.CLOCK);
        }
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void setContent(BusinessSmsMessage message, boolean isRebind) throws Exception {
        // TODO Auto-generated method stub
        super.setContent(message, isRebind);
        this.mMessage = message;
        initData(isRebind);
        bindTrainTickeInfo(mCurrentListIndex);
        /* SMARTISAN-375 zhaoxiachao 20161231 start */
        initListener();
        /* SMARTISAN-375 zhaoxiachao 20161231 end */
        message.putValue(ChannelContentUtil.IS_TRAINS + "", "true");
        updateReceiverState();
    }

    @SuppressLint("ResourceAsColor")
    private void initData(boolean isRebind) {
        if (ChannelContentUtil.bubbleDataIsNull(mMessage)) {
            return;
        }
        Object index = mMessage.getValue(SELECT_INDEX_KEY);
        if (index != null) {
            mCurrentListIndex = (Integer) index;
        } else {
            mCurrentListIndex = 0;
        }

        try {
            Object obTrain = mMessage.getValue("card_arr");
            if (obTrain == null) {
                return;
            }

            mTrainArray = (JSONArray) obTrain;
            int trainSize = mTrainArray.length();
            if (trainSize > 1) {
                /* SMARTISAN-434 zhaoxiachao 20170222 start */
                if(StringUtils.isNull(mMessage.getValue(ChannelContentUtil.BUBBLE_SIZE)+"")){
                    mMessage.putValue(ChannelContentUtil.BUBBLE_SIZE, trainSize);
                }
                /* SMARTISAN-434 zhaoxiachao 20170222 start */
                
                leftFirstTextIcon.setVisibility(View.VISIBLE);
                mTrainNumber.setOnClickListener(new OnClickDialog());
                mSelectArea.setOnClickListener(new OnClickDialog());
                ThemeUtil.setTextColor(Constant.getContext(), mTrainNumber, (String) mMessage.getValue("v_by_text_7"),
                        R.color.duoqu_theme_color_1100);
            } else {
                mTrainNumber.setOnClickListener(null);
                mSelectArea.setOnClickListener(null);
                leftFirstTextIcon.setVisibility(View.GONE);
                ThemeUtil.setTextColor(Constant.getContext(), mTrainNumber, (String) mMessage.getValue("v_by_text_8"),
                        R.color.duoqu_theme_color_3010);
            }

            if (mCurrentListIndex >= trainSize) {
                mCurrentListIndex = 0;
                mMessage.putValue(SELECT_INDEX_KEY, mCurrentListIndex);
            }

        } catch (Throwable e) {
            SmartSmsSdkUtil.smartSdkExceptionLog("BubbleTrainBody initData: " + e.getMessage(), e);
        }
    }

    private void bindTrainTickeInfo(int currentTrainIndex) {
        mMessage.putValue("db_train_data_index", currentTrainIndex);
        mCurrentListIndex = currentTrainIndex;
        mArriveCityListIndex = mMessage.bubbleJsonObj.optInt(DEPART_CURRENT, 0);
        train_data = (JSONObject) mTrainDataUtil.getViewContentData(mMessage);
        Log.i(TAG, "bindTrainTickeInfo: train_data" + train_data + " bubble:" + mMessage.bubbleJsonObj);
        if (train_data == null) {
            return;
        }

        mTrainNumberString = train_data.optString("view_m_trainnumber");
        mDepartCityString = train_data.optString("view_depart_city");
        mDepartDateString = train_data.optString("view_depart_date");
        mDepartTimeString = train_data.optString("view_depart_time");
        mArriveCityString = train_data.optString("view_arrive_city");
        mArriveDateString = train_data.optString("view_arrive_date");
        mArriveTimeString = train_data.optString("view_arrive_time");
        JSONArray seatInfoArray = train_data.optJSONArray("view_seat_info_list");
        String seatInfo = getSeatInfoString(seatInfoArray);
        mMessage.putValue("GROUP_KEY",
                mTrainNumberString.replace(" ", "").replace(ChannelContentUtil.TRAIN_SUPPLEMENT_NUMBER, ""));

        /* SMARTISAN-375 zhaoxiachao 20161231 start */
//        if (StringUtils.isNull(mMessage.getValue("arrive_city") + "")) {
//            mMessage.putValue("arrive_city", StringUtils.isNull(mArriveCityString));
//        }
        /* SMARTISAN-375 zhaoxiachao 20161231 end */

        Object hasSelect = mMessage.getValue("hasSelect" + mTrainDataUtil.getDataIndex(mMessage));
        Boolean hasQuery = mMessage.bubbleJsonObj.optBoolean("hasQuery" + mTrainDataUtil.getDataIndex(mMessage));
        Object supType = mMessage.bubbleJsonObj.optString("supplementType" + mTrainDataUtil.getDataIndex(mMessage));
        boolean isQuery = (hasQuery != null && hasQuery && supType != null);
        boolean isSelct = (hasSelect != null && (Boolean) hasSelect);
        if (isSelct) {
            mArriveCityString = mTrainDataUtil.getInterfaceTrainArriveCity(mMessage);
            if (StringUtils.isNull(mArriveCityString)) {
                mArriveCityString = ChannelContentUtil.TRAIN_SELECT_SITES;
            }
        }

        if (isSelct || supplementType_2.equals(supType)) {
            mArriveDateString = mTrainDataUtil.getInterfaceTrainArriveDate(mMessage);
            if (StringUtils.isNull(mArriveCityString)) {
                mArriveDateString = "";
            }

            mArriveTimeString = mTrainDataUtil.getInterfaceTrainArriveTime(mMessage);
            if (StringUtils.isNull(mArriveTimeString)) {
                mArriveTimeString = ChannelContentUtil.NO_DATA_EN;
            }
        }

        if (StringUtils.isNull(mDepartTimeString) && isQuery) {
            String departTimeStringQuery = mTrainDataUtil.getInterfaceTrainDepartTime(mMessage);
            if (!StringUtils.isNull(departTimeStringQuery)) {
                mDepartTimeString = departTimeStringQuery;
            }
        }

        upDateWithoutDate(mDepartCity, mWithoutDepartAddress, mDepartCityString);
        upDateWithoutDate(mDepartDate, mWithoutDepartDate, mDepartDateString);
        upDateWithoutTime(mDepartTime, mWithoutDepartTime, mDepartTimeString);
        ChannelContentUtil.setText(mTrainNumber, mTrainNumberString, "");
        LayoutParams param = (LayoutParams) mDateLayout.getLayoutParams();
        if (!StringUtils.isNull(seatInfo)) {
            mSecondSplit.setVisibility(View.VISIBLE);
            param.bottomMargin = ViewUtil.dp2px(Constant.getContext(), 0);
        } else {
            mSecondSplit.setVisibility(View.VISIBLE);
            if (mMessage.getTableDataSize(ChannelContentUtil.TABLE_KEY) != 0) {
                mSecondSplit.setVisibility(View.VISIBLE);
                param.bottomMargin = ViewUtil.dp2px(Constant.getContext(), 0);
            } else {
                mSecondSplit.setVisibility(View.GONE);
                param.bottomMargin = ViewUtil.dp2px(Constant.getContext(), 11);
            }
        }
        mDateLayout.setLayoutParams(param);
        /* SMARTISAN-265 zhaoxiachao 20161201 start */
        mMessage.putValue(ChannelContentUtil.SEAT_INFO, seatInfo);
        /* SMARTISAN-265 zhaoxiachao 20161201 end */
        setArriveInfo(mArriveCityString, mArriveDateString, mArriveTimeString);

        if (!isQuery) {
            if (StringUtils.isNull(mArriveCityString)) {
                queryTrainStation(supplementType_1);
            } else {
                if (StringUtils.isNull(mDepartTimeString) || StringUtils.isNull(mArriveDateString)
                        || StringUtils.isNull(mArriveTimeString)) {
                    queryTrainStation(supplementType_2);
                }
            }
        }
    }

    /* SMARTISAN-375 zhaoxiachao 20161231 start */
    @SuppressLint("ResourceAsColor")
    @Override
    public void initListener() throws Exception {
        try {
            if (mArriveLay != null) {
                String flag = train_data.optString("view_arrive_city");
                if (!StringUtils.isNull(flag)) {
                    mArriveLay.setOnClickListener(null);
                    rightLastTextIcon.setVisibility(View.GONE);

                    ThemeUtil.setTextColor(Constant.getContext(), mArriveCity, (String) mMessage.getValue("v_by_text_1"),
                            R.color.duoqu_theme_color_3010);
                } else {
                    mArriveLay.setOnClickListener(popupStationInfoListClickListener);
                    rightLastTextIcon.setVisibility(View.VISIBLE);
                    ThemeUtil.setTextColor(Constant.getContext(), mArriveCity, (String) mMessage.getValue("v_by_text_9"),
                            R.color.duoqu_theme_color_1100);
                }
            }
        } catch (Throwable ex) {
            SmartSmsSdkUtil.smartSdkExceptionLog(TAG, ex);
        }
    }

    /* SMARTISAN-375 zhaoxiachao 20161231 end */
    protected void queryTrainStation(final String type) {
        if (ChannelContentUtil.bubbleDataIsNull(mMessage)) {
            return;
        }
        mTrainDataUtil.queryTrainStation(mMessage, new SdkCallBack() {

            @Override
            public void execute(Object... obj) {
                if (queryFail(obj) || !mTrainDataUtil.dataBelongCurrentMsg(mMessage, obj) || mContext == null
                        || mContext.isFinishing()) {
                    return;
                }
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        trainDataCompletion(mMessage, type);
                    }
                });
            }

            private boolean queryFail(final Object... results) {
                return results == null || results.length != 2 || results[0] == null
                        || !(results[1] instanceof JSONArray);
            }
        }, type);
    }

    private String getSeatInfoString(JSONArray seatInfoArray) {
        if (seatInfoArray == null || seatInfoArray.length() < 1) {
            return null;
        }
        String seat = "";
        String carriage = "";
        String seatType = "";
        String sheets = "";
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < seatInfoArray.length(); i++) {
            JSONObject seatInfo = seatInfoArray.optJSONObject(i);
            if (seatInfo == null) {
                continue;
            }

            seat = seatInfo.optString("seat");
            carriage = seatInfo.optString("carriage");
            seatType = seatInfo.optString("seatType");
            if (!StringUtils.isNull(seat)) {
                if (i > 0) {
                    sb.append(ChannelContentUtil.TRAIN_SEAT_SPLIT);
                }
                if (!StringUtils.isNull(carriage)) {
                    sb.append(carriage);
                }
                sb.append(seat);
                if (!StringUtils.isNull(seatType)) {
                    sb.append(seatType);
                }
            } else if (!StringUtils.isNull(carriage) || !StringUtils.isNull(seatType)) {
                sheets = seatInfo.optString("sheets");
                if (i > 0) {
                    sb.append(ChannelContentUtil.TRAIN_SEAT_SPLIT);
                }
                if (!StringUtils.isNull(carriage)) {
                    sb.append(carriage);
                }
                if (!StringUtils.isNull(seatType)) {
                    sb.append(seatType);
                }
                if (!StringUtils.isNull(sheets)) {
                    sb.append(sheets);
                }
            }
        }

        return sb.toString();
    }

    private void setArriveInfo(String arriveCity, String arriveDate, String arriveTime) {
        this.mArriveCityString = arriveCity;
        this.mArriveDateString = arriveDate;
        this.mArriveTimeString = arriveTime;
        ChannelContentUtil.setText(mArriveCity, arriveCity, ChannelContentUtil.TRAIN_SELECT_SITES);
        upDateWithoutDate(mArriveDate, mWithoutArriveDate, arriveDate);
        upDateWithoutTime(mArriveTime, mWithoutArriveTime, arriveTime);
    }

    private void trainDataCompletion(BusinessSmsMessage message, String supType) {
        if (!TravelDataUtil.hasValue(mDepartTime, ChannelContentUtil.NO_DATA_EN)) {
            upDateWithoutTime(mDepartTime, mWithoutDepartTime, mTrainDataUtil.getInterfaceTrainDepartTime(mMessage));
        }

        if (supplementType_2.equals(supType)) {
            if (!TravelDataUtil.hasValue(mArriveDate, "")) {
                upDateWithoutDate(mArriveDate, mWithoutArriveDate, mTrainDataUtil.getInterfaceTrainArriveDate(mMessage));
            }
            if (!TravelDataUtil.hasValue(mArriveTime, ChannelContentUtil.NO_DATA_ARR_TIME)) {
                upDateWithoutTime(mArriveTime, mWithoutArriveTime, mTrainDataUtil.getInterfaceTrainArriveTime(mMessage));
            }
            if (!TravelDataUtil.hasValue(mDepartTime, ChannelContentUtil.NO_DATA_EN)) {
                upDateWithoutTime(mDepartTime, mWithoutDepartTime, mTrainDataUtil.getInterfaceTrainDepartTime(mMessage));
            }
        }
    }

    // 实现底部弹出列表的选中监听
    private class Onclick implements AirTrainSelectDialog.OnBottomClick {
        @Override
        public void Onclick(int type, int select) {
            // TODO Auto-generated method stub
            switch (type) {
            case AirTrainSelectDialog.CONFIRM:
                mCurrentListIndex = select;
                mMessage.putValue(SELECT_INDEX_KEY, mCurrentListIndex);
                bindTrainTickeInfo(mCurrentListIndex);
                HashMap<String, Object> param = new HashMap<String, Object>();
                String groupValue = "do";
                param.put("type", BasePopupView.CHANGE_DATA_TYPE_ALL);
                param.put("groupValue", groupValue);
                param.put(ChannelContentUtil.CHANGE_TRAIN, "true");

                if (mBasePopupView != null) {
                    mBasePopupView.changeData(param);
                }
                break;
            default:
                break;
            }
        }
    }

    // 点击选择车次监听
    private class OnClickDialog implements OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            AirTrainSelectDialog dialog = new AirTrainSelectDialog(mTrainArray, mContext, mCurrentListIndex,
                    ChannelContentUtil.IS_TRAINS);
            dialog.mParams.mSelectItemKey = "view_m_trainnumber";
            dialog.mParams.mDefaultTitleName = mTrainSelectString;
            dialog.showAlertDialog(new Onclick());
        }
    }

    /* SMARTISAN-375 zhaoxiachao 20161231 start */
    OnClickListener popupStationInfoListClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                if (mTrainNumber != null && mDepartCity != null && mDepartCity != null && mArriveCity != null) {
                    Map<String, Object> extend = new HashMap<String, Object>();
                    extend.put("phoneNumber", mMessage.getValue("phoneNum"));
                    extend.put("titleNo", mMessage.getValue("title_num"));
                    extend.put("bubbleJsonObj", mMessage.bubbleJsonObj.toString());
                    extend.put("messageBody", mMessage.getMessageBody());
                    extend.put("notSaveToDb", "false");
                    long departTime = mTrainArray.optJSONObject(mCurrentListIndex).optLong("view_depart_date_time");
                    final String date = ContentUtil.getFormatDate(new Date(departTime), new SimpleDateFormat("yyyy-MM-dd"));
                    extend.put("day", date);
                    ParseManager.queryTrainInfo(mMessage.getSmsId() + "", mTrainNumber.getText().toString(),
                            mDepartCity.getText().toString(), mArriveCity.getText().toString(), extend,
                            new SdkCallBack() {
                        @Override
                        public void execute(final Object... resultObj) {
                            mContext.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    if (resultObj == null || resultObj.length < 1 || resultObj[0] == null) {
                                        Toast toast = Toast.makeText(mContext, ChannelContentUtil.TRAIN_DATA_QUERY_ERROR, Toast.LENGTH_SHORT);
                                        toast.setDuration(1500);
                                        toast.show();
                                        return;
                                    }else if("offNetwork".equalsIgnoreCase(resultObj[0]+"")){
                                        Toast toast = Toast.makeText(mContext, ChannelContentUtil.TRAIN_DATA_OFF_NETWORK, Toast.LENGTH_SHORT);
                                        toast.setDuration(1500);
                                        toast.show();
                                        return;
                                    }
                                    /* SMARTISAN-461 zhaoxiachao 20170306 start */
                                    else if("timeOut".equalsIgnoreCase(resultObj[1]+"")){
                                        Toast toast = Toast.makeText(mContext, ChannelContentUtil.TRAIN_NUMBER_OVERDUE, Toast.LENGTH_SHORT);
                                        toast.setDuration(1500);
                                        toast.show();
                                        return;
                                    }
                                    /* SMARTISAN-461 zhaoxiachao 20170306 end */
                                    
                                    mArriveCityResultData = (JSONObject) resultObj[1];
                                    if(!mArriveCityResultData.optString("day").contains(date)){
                                        Toast toast = Toast.makeText(mContext, ChannelContentUtil.TRAIN_DATA_QUERY_ERROR, Toast.LENGTH_SHORT);
                                        toast.setDuration(1500);
                                        toast.show();
                                        return;
                                    }
                                    
                                    mArriveCityArr = mArriveCityResultData.optJSONArray("station_list");
                                    TrainArriveSelectDialog dialog = new TrainArriveSelectDialog(mArriveCityArr,
                                            mContext, mArriveCityListIndex, ChannelContentUtil.IS_TRAINS, mDepartCityString);
                                    dialog.mParams.mDefaultTitleName = ChannelContentUtil.TRAIN_SELECT_SITES;
                                    dialog.showTrainArriveDialog(new OnTrainClick());
                                }
                            });
                        }
                    });
                }
            } catch (Throwable ex) {
                SmartSmsSdkUtil.smartSdkExceptionLog(TAG, ex);
            }
        }
    };
    
    
    
 // arrive city item click layout
    private class OnTrainClick implements TrainArriveSelectDialog.OnBottomClick {
        @Override
        public void Onclick(int type, int select) {
            try {
                switch (type) {
                case AirTrainSelectDialog.CONFIRM:
                    if (mArriveCityArr == null) {
                        return;
                    }
                    mArriveCityListIndex = select;
                    JSONObject selObj = mArriveCityArr.optJSONObject(select);
                    String arriveDate = parseArriveDate(selObj, mArriveCityResultData.optString("day"), mArriveCityResultData.optString("start_time"));
                    String arriveCity = selObj.optString("name");
                    String arriveTime = selObj.optString("spt");
                    mMessage.bubbleJsonObj.put(mTrainDataUtil.getInterfaceTrainArriveCityKey(mMessage), arriveCity);
                    mMessage.bubbleJsonObj.put(mTrainDataUtil.getInterfaceTrainArriveDateKey(mMessage), arriveDate);
                    mMessage.bubbleJsonObj.put(mTrainDataUtil.getInterfaceTrainArriveTimeKey(mMessage), arriveTime);
                    mMessage.bubbleJsonObj.put(DEPART_CURRENT, mArriveCityListIndex);
                    mMessage.putValue("hasSelect" + mTrainDataUtil.getDataIndex(mMessage), true);
                    ParseManager.updateMatchCacheManager(mMessage);
                    setArriveInfo(arriveCity, arriveDate, arriveTime);
                    break;
                default:
                    break;
                }
            } catch (Throwable ex) {
                SmartSmsSdkUtil.smartSdkExceptionLog(TAG, ex);
            }
        }
    }
    
    /**
     * 将返回的数据， 转换所需要的时间
     * 
     * @param selObj
     * @return
     */
    private String parseArriveDate(JSONObject selObj, String departDate, String departTime) {
        String resultDate = "";
        Long resultDatel = 0l;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            long day = dateFormat.parse(departDate+ " "+departTime).getTime();
            // 获取运行时间
            String travelTime = selObj.optString("travel_time");
            Long travelTimel = TrainDataUtil.timeStrTolong(travelTime);
            resultDatel = day+travelTimel;
            dateFormat = new SimpleDateFormat(ChannelContentUtil.TRAIN_DATE_FORMAT);
            resultDate = dateFormat.format(resultDatel);
        } catch (Throwable ex) {
            SmartSmsSdkUtil.smartSdkExceptionLog(TAG, ex);
        }
        return resultDate;
    }
    /* SMARTISAN-375 zhaoxiachao 20161231 end */

    private boolean isOverClick() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
            lastClickTime = currentTime;
            return false;
        }
        return true;
    }

    private void upRegisterReceiver() {
        if (mRecerver != null) {
            try {
                mContext.unregisterReceiver(mRecerver);
                mRecerver = null;
            } catch (Throwable e) {
                mRecerver = null;
            }
        }
    }

    private void registerReceiver() {
        try {
            if (mRecerver == null) {
                mRecerver = new TrianStationSelectedReceiver(this);
            } else {
                mRecerver.setItem(this);
            }
            mContext.registerReceiver(mRecerver, new IntentFilter((String) mResverFilag));
        } catch (Throwable e) {
            SmartSmsSdkUtil.smartSdkExceptionLog("BubbleTrainBodyTtem: registerReceiver : " + e.getMessage(), e);
        }
    }

    static class TrianStationSelectedReceiver extends BroadcastReceiver {
        public void setItem(BubbleTrainBody item) {
            this.item = item;
        }

        private BubbleTrainBody item;

        public TrianStationSelectedReceiver(BubbleTrainBody item) {
            this.item = item;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (item == null)
                return;
            item.onReciver(intent);
            item = null;
        }
    }

    public void onReciver(Intent intent) {
        try {
            if (mMessage == null || mMessage.bubbleJsonObj == null)
                return;
            mContext.unregisterReceiver(mRecerver);
            String action = intent.getAction();
            if (!mResverFilag.equals(action))
                return;
            String key = intent.getStringExtra("JSONDATA");
            if (StringUtils.isNull(key))
                return;
            String chect = null;
            String arriveCity = null;
            String arriveDate = null;
            String arriveTime = null;

            JSONObject jsonDataObject = new JSONObject(key);

            chect = jsonDataObject.optString("checkString");
            arriveCity = jsonDataObject.optString("view_arrive_city");
            SimpleDateFormat format_1 = new SimpleDateFormat("yyyy-MM-dd");
            String str = jsonDataObject.optString("view_arrive_date");
            if (!StringUtils.isNull(str)) {
                Date date = format_1.parse(str);
                arriveDate = format.format(date);
            }
            arriveTime = jsonDataObject.optString("view_arrive_time");

            if (chect == null || !chect.equals(mChectString)) {
                return;
            }

            if (StringUtils.isNull(arriveCity) || StringUtils.isNull(arriveDate) || StringUtils.isNull(arriveTime)) {
                return;
            }

            mMessage.bubbleJsonObj.put(mTrainDataUtil.getInterfaceTrainArriveCityKey(mMessage), arriveCity);
            mMessage.bubbleJsonObj.put(mTrainDataUtil.getInterfaceTrainArriveDateKey(mMessage), arriveDate);
            mMessage.bubbleJsonObj.put(mTrainDataUtil.getInterfaceTrainArriveTimeKey(mMessage), arriveTime);

            mMessage.putValue("hasSelect" + mTrainDataUtil.getDataIndex(mMessage), true);
            ParseManager.updateMatchCacheManager(mMessage);
            setArriveInfo(arriveCity, arriveDate, arriveTime);
        } catch (Throwable e) {
            SmartSmsSdkUtil.smartSdkExceptionLog("BubbleTrainBody onReciver error:", e);
        }
    }

    private String getCheckString(BusinessSmsMessage message, int dataIndex) {
        String checkString = "";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(((JSONObject) mTrainDataUtil.getViewContentData(message)).optString("view_train_number"));
        stringBuilder.append(System.currentTimeMillis() + "");
        stringBuilder.append(String.valueOf(message.getSmsId()));
        stringBuilder.append(dataIndex + "");
        checkString = stringBuilder.toString();
        message.putValue(MESSAGE_CHECK_KEY, checkString);
        return checkString;
    }

    private void updateReceiverState() {
        if (mMessage == null) {
            return;
        }
        String checkString = (String) mMessage.getValue(MESSAGE_CHECK_KEY);

        if (!StringUtils.isNull(checkString)) {
            mChectString = checkString;
            registerReceiver();
        } else {
            upRegisterReceiver();
        }
    }

    @Override
    public void changeData(Map<String, Object> param) {
        try {
            /* SMARTISAN-261 zhaoxiachao 20161129 start */
            if (param != null && !StringUtils.isNull(param.get(ChannelContentUtil.CHANGE_TRAIN) + "")) {
                return;
            }
            /* SMARTISAN-261 zhaoxiachao 20161129 end */

            Object ob = param.get("adjust_data");
            if (ob != null) {
                setUpScheduleData(ob);
                return;
            }
        } catch (Throwable e) {
        }
    }

    private void setUpScheduleData(Object ob) {
        if (ob == null || !(ob instanceof HashMap<?, ?>) || mToWebActivityJsonObject == null) {
            return;
        }

        try {
            HashMap<String, Object> msgData = (HashMap<String, Object>) ob;
            mChectString = getCheckString(mMessage, mCurrentListIndex);
            msgData.put("checkString", mChectString);
        } catch (Throwable e) {
        }
        registerReceiver();
    }

    @Override
    public void destroy() {
        try {
            mContext.unregisterReceiver(mRecerver);
        } catch (Throwable e) {

        }

        /* SMARTISAN-289 zhaoxiachao 20161202 start */
        mMessage.putValue(SELECT_INDEX_KEY, 0);
        /* SMARTISAN-289 zhaoxiachao 20161202 end */
    }

    private void upDateWithoutDate(TextView textview, ImageView imageView, String date) {
        if (StringUtils.isNull(date)) {
            textview.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
            imageView.setBackgroundResource(R.drawable.duoqu_v_by_text_n_1);
        } else {
            textview.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.GONE);
            textview.setText(date);
        }
    }

    private void upDateWithoutTime(TextView textview, ImageView imageView, String time) {
        if (StringUtils.isNull(time)) {
            textview.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
        } else {
            textview.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.GONE);
            textview.setText(time);
        }
    }

}
